//
//  WKCoinRechargeVC.m
//  LLWallet
//
//  Created by wangfei on 2025/9/19.
//

#import "WKCoinRechargeVC.h"
#import "Masonry.h"
#import "WKCoinVM.h"
#import "WKCoinVC.h"
#import <CoreImage/CoreImage.h>

// 颜色定义
#define RGB(r, g, b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0]
#define RGBAlpha(r, g, b, a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]

// 主色调
#define MainColor RGB(52, 120, 246)
// 辅助色
#define SecondaryColor RGB(245, 247, 250)
// 文字主色
#define TextMainColor RGB(30, 30, 30)
// 文字次要色
#define TextSecondaryColor RGB(100, 100, 100)
// 边框色
#define BorderColor RGB(220, 220, 220)

@interface WKCoinRechargeVC ()

@property (nonatomic, strong) UIView *contentView; // 用于scrollView内容布局
@property (nonatomic, strong) UIView *currencyContainer;
@property (nonatomic, strong) UIImageView *currencyImageView;
@property (nonatomic, strong) UILabel *currencyLabel;
@property (nonatomic, strong) UIImageView *arrowImageView;
@property (nonatomic, strong) UIView *qrCodeContainer;
@property (nonatomic, strong) UIImageView *qrCodeImageView;
@property (nonatomic, strong) UILabel *addressLabel;
@property (nonatomic, strong) UIView *buttonContainer;
@property (nonatomic, strong) UIButton *saveButton;
@property (nonatomic, strong) UIButton *copButton;
@property (nonatomic, strong) UIView *infoContainer;
@property (nonatomic, strong) UILabel *minRechargeLabel;
@property (nonatomic, strong) UILabel *minValueLabel;
@property (nonatomic, strong) UILabel *tipsTitleLabel;
@property (nonatomic, strong) UILabel *tipsContentLabel;
@property (nonatomic, strong) UIActivityIndicatorView *loadingIndicator;
@property (nonatomic, copy) NSString *currentAddress;
@property (nonatomic, strong) NSMutableArray<WKBiTypeInfoResp *> *currencies;

@property (nonatomic, strong) WKBiTypeInfoResp *currentModel;


@end

@implementation WKCoinRechargeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = SecondaryColor;
    self.currentAddress = @"";
    [self setupUI];
    [self loadData];
}

- (void)setupUI {
   
    // 滚动视图
    _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WKScreenWidth, 600)];
    self.tableView.tableHeaderView = _contentView;
        
    // 货币选择容器
    [self setupCurrencyContainer];
    
    // 二维码容器
    [self setupQrCodeContainer];
    
    // 地址和按钮
    [self setupAddressAndButtons];
    
    // 信息容器
    [self setupInfoContainer];
    
    // 提示信息
    [self setupTips];
    
    // 加载指示器
    [self setupLoadingIndicator];
}

- (NSString *)langTitle {
    return LLang(@"充值");
}
- (void)setupCurrencyContainer {
    _currencyContainer = [[UIView alloc] init];
    _currencyContainer.backgroundColor = [UIColor whiteColor];
    _currencyContainer.layer.cornerRadius = 10;
    _currencyContainer.layer.shadowColor = [UIColor blackColor].CGColor;
    _currencyContainer.layer.shadowOpacity = 0.05;
    _currencyContainer.layer.shadowOffset = CGSizeMake(0, 2);
    _currencyContainer.layer.shadowRadius = 4;
    [_contentView addSubview:_currencyContainer];
    [_currencyContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_contentView).offset(20);
        make.left.equalTo(_contentView).offset(15);
        make.right.equalTo(_contentView).offset(-15);
        make.height.mas_equalTo(60);
    }];
    // 箭头图标
    _currencyImageView = [[UIImageView alloc] init];
    _currencyImageView.contentMode = UIViewContentModeScaleAspectFit;
    [_currencyContainer addSubview:_currencyImageView];
    [_currencyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_currencyContainer);
        make.left.equalTo(_currencyContainer).offset(15);
        make.width.mas_equalTo(45);
        make.height.mas_equalTo(45);
    }];
    
    // 货币标签，显示当前选中的币种
    _currencyLabel = [[UILabel alloc] init];
    _currencyLabel.text = @"";
    _currencyLabel.textColor = TextMainColor;
    _currencyLabel.font = [UIFont boldSystemFontOfSize:17];
    [_currencyContainer addSubview:_currencyLabel];
    [_currencyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_currencyContainer);
        make.left.equalTo(_currencyImageView.mas_right).offset(15);
    }];
    
    // 箭头图标
    _arrowImageView = [[UIImageView alloc] init];
    _arrowImageView.image = [self imageName:@"arrow_right"];
    _arrowImageView.contentMode = UIViewContentModeScaleAspectFit;
    [_currencyContainer addSubview:_arrowImageView];
    [_arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_currencyContainer);
        make.right.equalTo(_currencyContainer).offset(-15);
        make.width.mas_equalTo(15);
        make.height.mas_equalTo(15);
    }];
    
    // 点击手势，用于选择货币
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(currencySelectAction)];
    _currencyContainer.userInteractionEnabled = YES;
    [_currencyContainer addGestureRecognizer:tapGesture];
}

- (void)setupQrCodeContainer {
    _qrCodeContainer = [[UIView alloc] init];
    _qrCodeContainer.backgroundColor = [UIColor whiteColor];
    _qrCodeContainer.layer.cornerRadius = 10;
    _qrCodeContainer.layer.shadowColor = [UIColor blackColor].CGColor;
    _qrCodeContainer.layer.shadowOpacity = 0.05;
    _qrCodeContainer.layer.shadowOffset = CGSizeMake(0, 2);
    _qrCodeContainer.layer.shadowRadius = 4;
    [_contentView addSubview:_qrCodeContainer];
    [_qrCodeContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_currencyContainer.mas_bottom).offset(15);
        make.left.right.equalTo(_currencyContainer);
        make.height.mas_equalTo(320);
    }];
    
    // 二维码图片
    _qrCodeImageView = [[UIImageView alloc] init];
    _qrCodeImageView.contentMode = UIViewContentModeScaleAspectFit;
    _qrCodeImageView.backgroundColor = [UIColor whiteColor];
    _qrCodeImageView.layer.borderColor = BorderColor.CGColor;
    _qrCodeImageView.layer.borderWidth = 1;
    _qrCodeImageView.layer.cornerRadius = 8;
    [_qrCodeContainer addSubview:_qrCodeImageView];
    [_qrCodeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_qrCodeContainer).offset(20);
        make.centerX.equalTo(_qrCodeContainer);
        make.width.height.mas_equalTo(200);
    }];
}

- (void)setupAddressAndButtons {
    // 地址标签
    _addressLabel = [[UILabel alloc] init];
    _addressLabel.numberOfLines = 0;
    _addressLabel.font = [UIFont systemFontOfSize:14];
    _addressLabel.textColor = TextSecondaryColor;
    _addressLabel.textAlignment = NSTextAlignmentCenter;
    _addressLabel.text = self.currentAddress;
    [_qrCodeContainer addSubview:_addressLabel];
    [_addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_qrCodeImageView.mas_bottom).offset(15);
        make.left.equalTo(_qrCodeContainer).offset(15);
        make.right.equalTo(_qrCodeContainer).offset(-15);
    }];
    
    // 按钮容器
    _buttonContainer = [[UIView alloc] init];
    [_qrCodeContainer addSubview:_buttonContainer];
    [_buttonContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_addressLabel.mas_bottom).offset(15);
        make.centerX.equalTo(_qrCodeContainer);
        make.left.greaterThanOrEqualTo(_qrCodeContainer).offset(15);
        make.right.lessThanOrEqualTo(_qrCodeContainer).offset(-15);
    }];
    
    // 保存按钮
    _saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_saveButton setTitle:@"保存二维码" forState:UIControlStateNormal];
    [_saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _saveButton.backgroundColor = MainColor;
    _saveButton.layer.cornerRadius = 20;
    _saveButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [_saveButton addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
    
    // 添加按钮点击效果
    [_saveButton addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
    [_saveButton addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel];
    
    [_buttonContainer addSubview:_saveButton];
    [_saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(_buttonContainer);
        make.width.mas_equalTo(120);
        make.height.mas_equalTo(40);
    }];
    
    // 复制按钮
    _copButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_copButton setTitle:@"复制地址" forState:UIControlStateNormal];
    [_copButton setTitleColor:MainColor forState:UIControlStateNormal];
    _copButton.backgroundColor = [UIColor whiteColor];
    _copButton.layer.borderColor = MainColor.CGColor;
    _copButton.layer.borderWidth = 1;
    _copButton.layer.cornerRadius = 20;
    _copButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [_copButton addTarget:self action:@selector(copyAction) forControlEvents:UIControlEventTouchUpInside];
    
    // 添加按钮点击效果
    [_copButton addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
    [_copButton addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel];
    
    [_buttonContainer addSubview:_copButton];
    [_copButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_saveButton.mas_right).offset(15);
        make.top.bottom.right.equalTo(_buttonContainer);
        make.width.mas_equalTo(120);
        make.height.mas_equalTo(40);
    }];
}

- (void)setupInfoContainer {
    _infoContainer = [[UIView alloc] init];
    _infoContainer.backgroundColor = [UIColor whiteColor];
    _infoContainer.layer.cornerRadius = 10;
    _infoContainer.layer.shadowColor = [UIColor blackColor].CGColor;
    _infoContainer.layer.shadowOpacity = 0.05;
    _infoContainer.layer.shadowOffset = CGSizeMake(0, 2);
    _infoContainer.layer.shadowRadius = 4;
    [_contentView addSubview:_infoContainer];
    [_infoContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_qrCodeContainer.mas_bottom).offset(15);
        make.left.right.equalTo(_currencyContainer);
        make.height.mas_equalTo(50);
    }];
    
    // 分隔线
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = BorderColor;
    [_infoContainer addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.equalTo(_infoContainer);
        make.height.mas_equalTo(0.5);
    }];
    
    // 最小充值数标签
    _minRechargeLabel = [[UILabel alloc] init];
    _minRechargeLabel.text = @"最小充值数量";
    _minRechargeLabel.font = [UIFont systemFontOfSize:15];
    _minRechargeLabel.textColor = TextSecondaryColor;
    [_infoContainer addSubview:_minRechargeLabel];
    [_minRechargeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_infoContainer);
        make.left.equalTo(_infoContainer).offset(15);
    }];
    
    // 最小充值数值标签
    _minValueLabel = [[UILabel alloc] init];
    _minValueLabel.text = @"0.0001";
    _minValueLabel.font = [UIFont boldSystemFontOfSize:15];
    _minValueLabel.textColor = TextMainColor;
    [_infoContainer addSubview:_minValueLabel];
    [_minValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_infoContainer);
        make.right.equalTo(_infoContainer).offset(-15);
    }];
}

- (void)setupTips {
    // 提示标题
    _tipsTitleLabel = [[UILabel alloc] init];
    _tipsTitleLabel.text = @"充值须知";
    _tipsTitleLabel.font = [UIFont boldSystemFontOfSize:16];
    _tipsTitleLabel.textColor = TextMainColor;
    [_contentView addSubview:_tipsTitleLabel];
    [_tipsTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_infoContainer.mas_bottom).offset(25);
        make.left.equalTo(_currencyContainer).offset(5);
    }];
    
    // 提示内容
    _tipsContentLabel = [[UILabel alloc] init];
    _tipsContentLabel.text = @"1. 请务必确认充值的币种和网络类型，错误的网络可能导致资产丢失\n2. 充值到账时间取决于区块链网络确认速度\n3. 如有任何问题，请联系客服";
    _tipsContentLabel.numberOfLines = 0;
    _tipsContentLabel.font = [UIFont systemFontOfSize:14];
    _tipsContentLabel.textColor = TextSecondaryColor;
    [_contentView addSubview:_tipsContentLabel];
    [_tipsContentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tipsTitleLabel.mas_bottom).offset(10);
        make.left.equalTo(_currencyContainer);
        make.right.equalTo(_currencyContainer);
    }];
}

- (void)setupLoadingIndicator {
    _loadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _loadingIndicator.hidesWhenStopped = YES;
    [_qrCodeContainer addSubview:_loadingIndicator];
    [_loadingIndicator mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_qrCodeImageView);
    }];
}

#pragma mark - 数据加载
- (void)loadData {
    [self requestData];
}

#pragma mark - 事件处理
- (void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)requestData{
    __weak typeof(self) weakSelf = self;
    self.currencies = [NSMutableArray array];
    [self.loadingIndicator startAnimating];
    [[WKAPIClient sharedClient] GET:@"udun/coin_types" parameters:nil].then(^(NSDictionary *resps){
        [self.loadingIndicator stopAnimating];
        NSArray *listArr = resps[@"coinTypes"];
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dic in listArr) {
            WKBiTypeInfoResp *model = [WKBiTypeInfoResp new];
            model._id = dic[@"id"];
            model.name = dic[@"name"];
            model.type = [dic[@"mainCoinType"] integerValue];
            model.logo = dic[@"logo"];
            model.coinName = dic[@"coinName"];
            [arr addObject:model];
        }
        self.currentModel = arr.firstObject;
    }).catch(^(NSError *error){
        [self.loadingIndicator stopAnimating];
    });
}

- (void)currencySelectAction {
    WKCoinVC *vc = [WKCoinVC new];
    vc.confirmBlock = ^(WKBiTypeInfoResp * _Nonnull item) {
        self.currentModel = item;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setCurrentModel:(WKBiTypeInfoResp *)currentModel{
    _currentModel = currentModel;
    
    self.currencyLabel.text = currentModel.name;
    [self.currencyImageView sd_setImageWithURL:[NSURL URLWithString:currentModel.logo?:@""]];
    //        self.currencyLabel.text = selectedCurrency.name;
    self.minValueLabel.text = [NSString stringWithFormat:@"0.0001 %@", [currentModel.name componentsSeparatedByString:@"-"].firstObject];
    
    // 模拟加载新币种的二维码和地址
   
//    self.qrCodeImageView.image = nil;
    
    [self changeQRCode];
}

- (void)changeQRCode{
    __weak typeof(self) weakSelf = self;
    [self.loadingIndicator startAnimating];
    NSInteger type = self.currentModel.type?:self.currentModel.type;
    
    [[WKAPIClient sharedClient] POST:@"udun/address" parameters:@{@"main_coin_type":@(type)}].then(^(NSDictionary *resps){
        [weakSelf.loadingIndicator stopAnimating];
        if ([resps isKindOfClass:[NSDictionary class]]){
            weakSelf.currentAddress = resps[@"address"];
            weakSelf.addressLabel.text = weakSelf.currentAddress;
            UIImage *qrCode = [weakSelf generateQRCodeWithString:weakSelf.currentAddress size:weakSelf.qrCodeImageView.frame.size.width];
            weakSelf.qrCodeImageView.image = qrCode;
        }
      
    }).catch(^(NSError *error){
        [weakSelf.loadingIndicator stopAnimating];
    });

}

- (void)saveAction {
    // 保存二维码逻辑
    if (!self.qrCodeImageView.image) {
        [self showToast:@"暂无二维码可保存"];
        return;
    }
    
    UIImageWriteToSavedPhotosAlbum(self.qrCodeImageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)copyAction {
    // 复制地址逻辑
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self.addressLabel.text;
    
    // 显示复制成功提示
    [self showToast:@"地址已复制"];
}

#pragma mark - 按钮点击效果
- (void)buttonTouchDown:(UIButton *)button {
    button.alpha = 0.7;
}

- (void)buttonTouchUp:(UIButton *)button {
    button.alpha = 1.0;
}

#pragma mark - 辅助方法
- (void)showToast:(NSString *)message {
    // 检查是否已有toast
    UIView *existingToast = [self.view viewWithTag:1000];
    if (existingToast) {
        [existingToast removeFromSuperview];
    }
    
    UIView *toastView = [[UIView alloc] init];
    toastView.tag = 1000;
    toastView.backgroundColor = RGBAlpha(0, 0, 0, 0.7);
    toastView.layer.cornerRadius = 4;
    [self.view addSubview:toastView];
    [toastView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-80);
    }];
    
    UILabel *toastLabel = [[UILabel alloc] init];
    toastLabel.text = message;
    toastLabel.textColor = [UIColor whiteColor];
    toastLabel.font = [UIFont systemFontOfSize:14];
    [toastView addSubview:toastLabel];
    [toastLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(toastView).insets(UIEdgeInsetsMake(8, 12, 8, 12));
    }];
    
    // 动画显示和隐藏
    toastView.alpha = 0;
    [UIView animateWithDuration:0.3 animations:^{
        toastView.alpha = 1;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 delay:1.5 options:0 animations:^{
            toastView.alpha = 0;
        } completion:^(BOOL finished) {
            [toastView removeFromSuperview];
        }];
    }];
}

- (UIImage *)generateQRCodeWithString:(NSString *)string size:(CGFloat)size {
    if (!string.length) {
        return nil;
    }
    
    // 将字符串转换为数据
    NSData *stringData = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    // 创建二维码滤镜
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    // 设置纠错级别 L(7%)、M(15%)、Q(25%)、H(30%)
    [qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
    
    // 获取生成的CIImage
    CIImage *qrImage = qrFilter.outputImage;
    
    // 调整二维码大小
    CGRect extent = CGRectIntegral(qrImage.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    
    // 创建位图上下文
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:qrImage fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 获取最终的CGImage
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    // 释放资源
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    CGColorSpaceRelease(cs);
    
    // 转换为UIImage并返回
    return [UIImage imageWithCGImage:scaledImage];
}

#pragma mark - UIImageWriteToSavedPhotosAlbum回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error) {
        [self showToast:@"保存失败"];
    } else {
        [self showToast:@"二维码已保存到相册"];
    }
}

-(UIImage*) imageName:(NSString*)name {
    return [[WKApp shared] loadImage:name moduleID:@"LLWallet"];
}
@end
